<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
namespace App\Exception\Handler;

use Hyperf\Context\Context;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

class ErrorExceptionHandler extends ExceptionHandler
{
    public function handle(\Throwable $throwable, ResponseInterface $response)
    {
        // 判断被捕获到的异常是希望被捕获的异常

        if (get_class($throwable) == 'Error') {
            $message = $throwable->getMessage();
            $errorS = [
                'Call to a member function update() on null',
                'Call to a member function delete() on null',
                'Call to a member function save() on null',
                'Call to a member function destroy() on null',
                'Call to a member function pluck() on null',
            ];

            if (in_array($message, $errorS)) {
                // 格式化输出
                $data = json_encode([
                    'code' => 10000,
                    'msg' => $message, // '方法不存在异常',
                    'data' => [],
                ], JSON_UNESCAPED_UNICODE);

                // 阻止异常冒泡
                $this->stopPropagation();
                $request = Context::get(ServerRequestInterface::class);
                return $response->withStatus(422)
                    ->withHeader('Content-type', 'application/json; charset=utf-8')
                    // ->withHeader('Access-Control-Allow-Origin', config('cors'))
                    ->withHeader('Access-Control-Allow-Origin', $request->getHeaderLine('origin'))
                    ->withHeader('Access-Control-Allow-Credentials', 'true')
                    ->withHeader('Access-Control-Allow-Headers', 'DNT,Keep-Alive,User-Agent,Cache-Control,Content-Type,Authorization')
                    ->withBody(new SwooleStream($data));
            }
            return $response;
        }

        // 交给下一个异常处理器
        return $response;
        // 或者不做处理直接屏蔽异常
    }

    /**
     * 判断该异常处理器是否要对该异常进行处理.
     */
    public function isValid(\Throwable $throwable): bool
    {
        return true;
    }
}
